package com.atguigu.aiproject.utils;

import jakarta.servlet.http.HttpServletRequest;

public final class HttpUtils {
    // 禁止实例化，禁止继承
    private HttpUtils() {}
    /**
     * 获取客户端真实IP地址
     * @param request HttpServletRequest对象
     * @return 客户端真实IP地址
     */
    public static String getClientIpAddress(HttpServletRequest request) {
        String ip = null;

        // 优先获取常见的代理设置的请求头
        for (String header : new String[]{
                "X-Forwarded-For",
                "X-Real-IP",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_CLIENT_IP",
                "HTTP_X_FORWARDED_FOR"}
        ) {
            ip = request.getHeader(header);
            if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
                break;
            }
        }

        // 如果通过代理获取到了IP，但其中可能包含多个IP地址，第一个才是真实客户端IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }

        // 如果没有通过代理获取到IP，则使用原始方式获取
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    public static String getTokenFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        return null;
    }
}
